package com.example.demo.codegenerate.util;

import com.example.demo.codegenerate.domain.DatabaseColumn;
import com.example.demo.codegenerate.domain.DatabaseTable;
import com.example.demo.codegenerate.domain.JeecgColumn;
import com.example.demo.codegenerate.domain.JeecgTable;
import org.apache.commons.beanutils.BeanMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CodeGenerateUtil {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public static Map renderParameter(String _package, JeecgTable jeecgTable){
        Map map = new HashMap();

        map.put("package", _package);
        map.put("comment", jeecgTable.getComment());
        map.put("databaseTableName", jeecgTable.getName());
        map.put("className", underline2Camel(jeecgTable.getName(), false));
        map.put("classNameFirstLower", underline2Camel(jeecgTable.getName(), true));

        List<Map> columns = new ArrayList<Map>();
        jeecgTable.getJeecgColumnList().forEach(jeecgColumn -> {
            Map columnMap = beanToMap(jeecgColumn);
            columnMap.put("javaPropertyName", underline2Camel(jeecgColumn.getName(), true));
            columnMap.put("javaPropertyNameFirstUpper", underline2Camel(jeecgColumn.getName(), false));
            columns.add(columnMap);
        });
        map.put("columns", columns);
        return map;
    }

    public static DatabaseTable jeecgTable2databaseTable(JeecgTable jeecgTable) {
        DatabaseTable databaseTable = new DatabaseTable();

        databaseTable.setName(jeecgTable.getName());
        databaseTable.setComment(jeecgTable.getComment());

        List<DatabaseColumn> columns = new ArrayList<DatabaseColumn>();
        databaseTable.setColumns(columns);

        List<JeecgColumn> jeecgColumnList = jeecgTable.getJeecgColumnList();
        jeecgColumnList.forEach(jeecgColumn -> {
            DatabaseColumn databaseColumn = new DatabaseColumn();
            columns.add(databaseColumn);

            databaseColumn.setName(jeecgColumn.getName());
            databaseColumn.setComment(jeecgColumn.getComment());
            databaseColumn.setMaxLength(jeecgColumn.getMaxLength());
            databaseColumn.setNullable(jeecgColumn.isNullable());
            databaseColumn.setType(jeecgColumn.getDatabaseType());
            databaseColumn.setUnique(jeecgColumn.isUq());
            databaseColumn.set_default(jeecgColumn.get_default());
        });

        return databaseTable;
    }

    /**
     * 下划线转驼峰法
     * @param line 源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰
     * @return 转换后的字符串
     */
    public static String underline2Camel(String line,boolean smallCamel){
        if(line==null||"".equals(line)){
            return "";
        }
        StringBuffer sb=new StringBuffer();
        Pattern pattern= Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(smallCamel&&matcher.start()==0?Character.toLowerCase(word.charAt(0)):Character.toUpperCase(word.charAt(0)));
            int index=word.lastIndexOf('_');
            if(index>0){
                sb.append(word.substring(1, index).toLowerCase());
            }else{
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }
    /**
     * 驼峰法转下划线
     * @param line 源字符串
     * @return 转换后的字符串
     */
    public static String camel2Underline(String line){
        if(line==null||"".equals(line)){
            return "";
        }
        line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
        StringBuffer sb=new StringBuffer();
        Pattern pattern=Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end()==line.length()?"":"_");
        }
        return sb.toString();
    }

    /**
     * 将对象装换为map
     * @param bean
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = new BeanMap(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key+"", beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * java类型对应
     * @param javaType
     * @return
     */
    public static String javaType2databaseType(String javaType, String ctrlType){
        switch (javaType){
            case "Integer":
                return "INTEGER";
            case "Double":
                return "DOUBLE";
            case "Date":
                return "TIMESTAMP";
            case "Boolean":
                return "BIT";
            case "String":
                return ctrlType2databaseType(ctrlType);
            default:
                return "VARCHAR";
        }
    }

    public static String ctrlType2databaseType(String ctrlType){
        switch (ctrlType){
            case "text":
            case "password":
            case "select":
            case "radio":
            case "image":
            case "file":
                return "VARCHAR";
            case "datetime":
                return "TIMESTAMP";
            case "textarea":
                return "TEXT";
            case "ckeditor":
                return "LONGTEXT";
            default:
                return "VARCHAR";
        }
    }
}
